import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras,ActivatedRoute } from '@angular/router';
import { AlertController } from '@ionic/angular';
import {TranslateService} from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import {CustomToastProviderService} from '@common-components/common-toast/custom-toast-provider.service';
import { HttpClient } from "@angular/common/http";
import { AuthTokenService } from '@services/auth-token.service';
import { EncryptService } from '@services/encrypt.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppParam } from '@services/common-service.service';
@Component({
  selector: 'app-payment-settings',
  templateUrl: './payment-settings.page.html',
  styleUrls: ['./payment-settings.page.scss'],
})
export class PaymentSettingsPage implements OnInit {
  inner: boolean = true;
  options = [];

  changeOptionToggle(evt,option){
 

    if (evt.srcElement.checked) {
      option.optionEnable = false;
    }else{
      option.optionEnable = true;
    }

    if(option.optionEnable){
      this.optionEnable(option);
    }else{
      this.optionClose(option);
    }
  }
  async optionEnable(option){
    const alert = await this.alertController.create({
      header: 'Please enter payment password',
      inputs: [
        {
          name: 'paymentPwd',
          type: 'password',
          placeholder: 'Password'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (data) => {
  
            option.optionEnable=false;
          }
        }, {
          text: 'Confirm',
          handler: (data) => {

            this.togglePayment({
              paymentPwd:data.paymentPwd,
              type:option.id,
              close:false,
              data:option
            });
            // if(this.openSuccessfully){
            //   option.optionEnable=true;
            // }
            // this.openSuccessfully=false;
          }
        }
      ]
    });
    await alert.present();
  }

  async optionClose(option){
    let header = '';
    if(option.id==='4'){
      header='Do you want to close Face ID Pay?';
    }else{
      header='Do you want to close Touch ID Pay?';
    }
    const alert = await this.alertController.create({
      header: header,
      // header: 'Please enter payment password',
      inputs: [
        {
          name: 'paymentPwd',
          type: 'password',
          placeholder: 'Password'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (data) => {
    
            // this.togglePayment({
            //   paymentPwd:data.paymentPwd,
            //   type:option.id,
            //   close:true
            // });
            option.optionEnable=true;
          }
        }, {
          text: 'Confirm',
          handler: (data) => {
         
            this.togglePayment({
              paymentPwd:data.paymentPwd,
              type:option.id,
              close:true,
              data:option
            });
            // if(this.openSuccessfully){
            //   option.optionEnable=false;
            // }
            // this.openSuccessfully=false;
            // option.optionEnable=false;
          }
        }
      ]
    });
    await alert.present();
  }

  commonResponseShow(response,options){
    if(response.responseBody != 1){
      this.customToast.show({
        icon:false,
        iconSuccess:false,
        message:"Payment Password error",
        duration:2000
      });
      this.openSuccessfully = false;
      if(options.close){
        options.data.optionEnable=true;
      }else{
        options.data.optionEnable=false;
      }
    }else{
      this.openSuccessfully = true;
      if(options.close){
        options.data.optionEnable=false;
      }else{
        options.data.optionEnable=true;
      }
    }
  }

  openSuccessfully = false;
  togglePayment(options){
    let url = '/scm/app/changePaymentPwd.do';
    if(options.paymentPwd){
      options.paymentPwd = this.encryptService.md5Ecrypt(options.paymentPwd);
    }
    if(options.close){
      if(options.type=="4"){
        let requestData = {
          appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
          paymentPassword:options.paymentPwd,
          enableFacePay:false
        };
        // data.resetPwd=false;
        this.http.post(url, requestData).subscribe((response: any) => {
          // location.reload(true);
          // location.replace(location.pathname);
          this.commonResponseShow(response,options);
        });
      }else{
        let requestData = {
          appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
          paymentPassword:options.paymentPwd,
          enableTouchPay:false
        };
        // data.resetPwd=false;
        this.http.post(url, requestData).subscribe((response: any) => {
          // location.reload(true);
          // location.replace(location.pathname);
          this.commonResponseShow(response,options);
        });
      }
    }else{
      if(options.type=="4"){
        let requestData = {
          appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
          paymentPassword:options.paymentPwd,
          enableFacePay:true
        };
        // data.resetPwd=false;
        this.http.post(url, requestData).subscribe((response: any) => {
          // location.reload(true);
          // location.replace(location.pathname);
          this.commonResponseShow(response,options);
        });
      }else{
        let requestData = {
          appUserId:this.appUserId,//this.authTokenService.getAppUserId(),
          paymentPassword:options.paymentPwd,
          enableTouchPay:true
        };
        // data.resetPwd=false;
        this.http.post(url, requestData).subscribe((response: any) => {
          // location.reload(true);
          // location.replace(location.pathname);
          this.commonResponseShow(response,options);
        });
      }
    }
  }



  i18n : any;
  initTables(){
    this.options = [
      {
        id:'1',
        title:this.i18n.payment_password,
        icon:'',
        path:'/tabs/myAccount/setting/payment-settings/payment-password',
        toggle:false
      },
      { 
        id:'2',
        title:this.i18n.micro_payments,
        icon:'',
        path:'/tabs/myAccount/setting/payment-settings/free-payment',
        toggle:false
      },
      { 
        id:'3',
        title:this.i18n.deductions_order,
        icon:'',
        path:'/tabs/myAccount/setting/payment-settings/deduction-order',
        toggle:false
      },
      {
        id:'4',
        title:this.i18n.face_pay,
        icon:'',
        path:'',
        toggle:true,
        optionEnable:false
      },
      {
        id:'5',
        title:this.i18n.touch_pay,
        icon:'',
        path:'',
        toggle:true,
        optionEnable:false
      }
    ];
  }

  appUserId = this.authTokenService.getAppUserId();
  constructor(
    private router:Router,
    private route : ActivatedRoute,
    private alertController:AlertController,
    private translate: TranslateService,
    private http: HttpClient,
    private authTokenService: AuthTokenService,
    private encryptService:EncryptService,
    private defaultLanguageService:DefaultLanguageService,
    private customToast:CustomToastProviderService,
    private commonService:CommonService
  ) { 
    this.i18n = this.commonService.initTranslate(['myAccount.setting.payment_settings']);
    this.initTables();
    this.route.data.subscribe((obj)=>{
        let facePay  = this.options.find(value=>value.id == '4');
        let touchPay = this.options.find(value=>value.id == '5');
        let body = obj.data.responseBody;
        facePay.optionEnable = body.enableFacePay;
        touchPay.optionEnable = body.enableTouchPay;
    });
  }

  ngOnInit() {
    this.route.queryParams.subscribe((data)=>{
   
      let alertController = this.alertController;
      let toast = {
        icon:true,
        iconSuccess:true,
        message:data.text,
        duration:2000
      };
      if(data.createPaymentPwd){
        this.customToast.show(toast);
        // setTimeout(() => {
        //   location.replace(location.pathname);
        // }, 2100);
      }
      if(data.closeMicroPayment){
        this.customToast.show(toast);
        // setTimeout(() => {
        //   location.replace(location.pathname);
        // }, 2100);
      }
    });
  }

  showDetail(evt,id){
    const option = this.options.find(tech => tech.id === id);
    if(option.path){
      this.router.navigate([option.path]);
    }
  }
}
